package com.m1905.lib.download.task;



import com.m1905.lib.download.model.DownloadDBItem;
import com.m1905.lib.download.util.DLog;
import com.m1905.lib.download.util.DownloadPreferences;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

/**
 * @author wanghao
 * @date 2023/10/12.
 * @des
 */
public abstract class BaseTask implements Runnable {

    protected DownloadDBItem item;

    protected Future future;

    public BaseTask() {

    }

    public void executeOnExecutor(DownloadDBItem item) {
        this.item = item;
        DLog.e("BaseTask executeOnExecutor ");
        future = DownloadPreferences.getExecutor(item.getType()).submit(this);
    }

    public void abortedRequest() {
        if (future != null) {
            future.cancel(true);
        }
        future = null;
    }

    @Override
    public void run() {
        List<Interceptor> ls = new ArrayList<>();
        List<Interceptor> interceptors = DownloadPreferences.getTaskInterceptor(item.getType());
        if (interceptors != null && interceptors.size() > 0) {
            ls.addAll(interceptors);
        }
        ls.add(new RealCall());
        new Interceptor.ApplicationInterceptorChain(0, ls, item).proceed(item);
    }

    public abstract void startDownload(String urlStr, String fileSavePath, long totalSize, boolean autoResume);

    public class RealCall implements Interceptor {

        @Override
        public DownloadDBItem intercept(Chain chain) {
            item = chain.request();
            if (item != null) {
                startDownload(item.getUrl(), item.getPath(), item.getTotalSize(), item.isResume());
            }
            return chain.proceed(item);
        }
    }

}
